package edu.pku.sei.modeler.actions;

import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.gef.ui.actions.SelectionAction;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchPart;

import edu.pku.sei.modeler.images.ImageProvider;




public class DeleteFromDiagramAction extends SelectionAction {

	/**
	 * 
	 */
	public final static String DELETE_FROM_DIAGRAM_ACTION_REQUEST = "delete";

	/**
	 * 
	 */
	public final static String DELETE_FROM_DIAGRAM_ACTION_ID = "edu.pku.sei.modeler.action.deleteFromDiagram";

	private Request request;

	public DeleteFromDiagramAction(IWorkbenchPart part) {
		super(part);
		this.request = new Request(DELETE_FROM_DIAGRAM_ACTION_REQUEST);
		setText("Delete From Diagram");
		setId(DELETE_FROM_DIAGRAM_ACTION_ID);
		setToolTipText("Delete element(s) from the diagram");
		// ISharedImages sharedImages =
		// PlatformUI.getWorkbench().getSharedImages();
		setImageDescriptor(ImageProvider.getImageDescriptor(ImageProvider.PROJECT_CLOSED_IMG));
		setHoverImageDescriptor(getImageDescriptor());
	}

	@Override
	protected boolean calculateEnabled() {
		return canPerformAction();
	}

	private boolean canPerformAction() {
		
		if (getSelectedObjects().isEmpty()) {
			return false;
		}
		List parts = getSelectedObjects();
		for (int i = 0; i < parts.size(); i++) {
			Object o = parts.get(i);
			if (o instanceof edu.pku.sei.modeler.edit.parts.DiagramEditPart)
				return false;
		}
		return true;
	}

	private Command getCommand() {
		List editparts = getSelectedObjects();
		CompoundCommand cc = new CompoundCommand();
		for (int i = 0; i < editparts.size(); i++) {
			EditPart part = (EditPart) editparts.get(i);
			cc.add(part.getCommand(request));
		}
		return cc;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.action.Action#run()
	 */
	@Override
	public void run() {
		// open dialog window
		BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
			public void run() {
				execute(getCommand());
			}
		});
	}

}
